package com.solution.util;

import java.io.StringWriter;
import java.util.Iterator;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;

public class MessageCreation {

	private static VelocityEngine ve;
	private static final Logger log = Logger.getLogger(MessageCreation.class);
	static{
		try{
			ve = new VelocityEngine();
			// for not logging anything through Velocity
			ve.setProperty("runtime.log.logsystem.class", "org.apache.velocity.runtime.log.NullLogSystem");
			ve.setProperty("resource.loader", "class");
            ve.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
			ve.init();
		}
		catch (Exception e) {
			log.error("Mail sender construction error", e);
			throw new RuntimeException(e);
		}
	}
	
	public static String getMessage(Map<String, String> variableStrings, String templateName){
		try {
			VelocityContext ctx = new VelocityContext();
			if (variableStrings != null) {
				Iterator<String> iter = variableStrings.keySet().iterator();
				if (iter != null) {
					while (iter.hasNext()) {
						String key = iter.next();
						ctx.put(key, variableStrings.get(key));
					}
				}
			}
			Template t = ve.getTemplate(templateName);
			StringWriter writer = new StringWriter();
			t.merge(ctx, writer);
			log.debug(writer.toString());
			return writer.toString();
		} catch (Exception e) {
			log.error("email creation error", e);
			return "";
		}
	}
}
